// import {
//   login,
//   logout,
//   getUserInfo,
//   getMessage,
//   getContentByMsgId,
//   hasRead,
//   removeReaded,
//   restoreTrash,
//   getUnreadCount
// } from '@/api/user'
import userApi from '@/api/user'
import Cookies from 'js-cookie'
import { setClientToken, getToken } from '@/libs/util'
import { Common } from '../../utils/common'

export default {
  state: {
    userName: '',
    userId: '',
    userAgentToken: '',
    avatorImgPath: '',
    token: getToken(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {},
    messageCheckAllowLogin: {
      code: null,
      data: null,
      message: null,
      success: true,
      totalPages: 0,
      totalRows: 0
    },
    companyName: '',
    companyID: ''
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = require('@/assets/images/default_photo1.png')
      console.log(state.avatorImgPath)
    },
    setUserId (state, id) {
      // console.log('%c user.js id: ', 'color:blue', id)
      state.userId = id
    },
    setUserName (state, name) {
      console.log('%c user.js name: ', 'color:blue', name)
      state.userName = name
    },
    setUserAgentToken (state, agentToken) {
      state.userAgentToken = agentToken
      console.log(agentToken)
    },
    setAccess (state, access) {
      state.access = access
    },
    setActionAccess (state, actionAccess) {
      state.actionAccess = actionAccess
    },
    setClientToken (state, token) {
      state.token = token
      setClientToken(token)
    },
    setCompanyID (state, companyID) {
      console.log(`%c user.js companyID: ${companyID}`, 'color:green')
      state.companyID = companyID
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    setMessageCheckAllowLogin (state, data) {
      state.messageCheckAllowLogin = data
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    },
    setCompanyName (state, companyName) {
      console.log(`%c user.js companyName: ${companyName}`, 'color:green')
      state.companyName = companyName
    },
    // setCompanyID (state, companyID) {
    //   console.log(`%c user.js companyID: ${companyID}`, 'color:green')
    //   state.companyID = companyID
    // },
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { userName, password }) {
      userName = userName.trim()
      return new Promise((resolve, reject) => {
        userApi.login({
          userName,
          password
        }).then(res => {
          console.log('登录res: ', res)
          const data = res.data
          // console.log(data)
          if (data.success) {
            // let access_arr = data.data.menus.map(item => {
            //   return item.code
            // })
            // console.log(access_arr)
            localStorage.setItem('clientLoginInfo', JSON.stringify(data))
            // commit('setClientToken', data.data.access_token)
            // commit('setUserId', data.data.userId)
            // commit('setAccess', access_arr)
            // commit('setUserName', data.data.name)
            // commit('setAvator', require('@/assets/images/default_photo1.png'))
            // // commit('setHasGetInfo', true)
            // commit('setCompanyID', data.data.companyId)
            // Common.setCookie('loginInfo', JSON.stringify(data), 7)
            // setClientToken
          } else {

          }
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      Cookies.set('clientToken', '')
      commit('setClientToken', '')
      commit('setAccess', [])
      localStorage.clear()
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }, params) {
      const data = JSON.parse(localStorage.getItem('clientLoginInfo'))
      // console.log(params)
      if (data) {
        let access_arr = data.data.menus.map(item => {
          return item.code
        })
        if (params.data) {
          let actionAccess_arr = data.data.menus.find(item => {
            return item.code === params.data
          })
          if (actionAccess_arr) {
            console.log('actionAccess_arr.actions: ', actionAccess_arr.actions)
            commit('setActionAccess', actionAccess_arr.actions)
          } else {
            // return false
          }
        } else {
          commit('setActionAccess', '')
        }
        console.log('获取用户相关信息')
        console.log('**********************')
        // console.log(data)
        commit('setAvator', require('@/assets/images/default_photo1.png'))
        commit('setUserName', data.data.name)
        commit('setUserId', data.data.userId)
        commit('setCompanyID', data.data.companyId)
        // commit('setUserAgentToken', data.agentToken)
        commit('setAccess', access_arr)
        commit('setHasGetInfo', true)
        // console.log(state)
        commit('setCompanyName', data.data.companyName)
        // commit('setCompanyId', data.data.companyId)
      } else {
        Cookies.set('clientToken', '')
        commit('setClientToken', '')
        commit('setAccess', [])
        window.location.href = '/login'
      }
    },
    // 判断是否其他地方登录
    getLodinStatus ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          userApi.CheckAllowLogin().then(res => {
            const data = res.data
            commit('setMessageCheckAllowLogin', data)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount ({ state, commit }) {
      // userApi.getUnreadCount().then(res => {
      //   const { data } = res
      //   commit('setMessageCount', data)
      //   // commit('setMessageCount', 0)
      // })
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList ({ state, commit }) {
      return new Promise((resolve, reject) => {
        userApi.getMessage().then(res => {
          const { unread, readed, trash } = res.data
          commit('setMessageUnreadList', unread.sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          commit('setMessageReadedList', readed.map(_ => {
            _.loading = false
            return _
          }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          commit('setMessageTrashList', trash.map(_ => {
            _.loading = false
            return _
          }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          userApi.getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        userApi.hasRead(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageUnreadList',
            to: 'messageReadedList',
            msg_id
          })
          commit('setMessageCount', state.unreadCount - 1)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        userApi.removeReaded(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageReadedList',
            to: 'messageTrashList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        userApi.restoreTrash(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageTrashList',
            to: 'messageReadedList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
